<?php
/**
 * Created by gjk7788@163.com.
 * User: Carl
 * Date: 2018/6/15
 * Time: 15:28
 */

namespace App;


trait RecordsActivity
{
    protected static function getActivitiesToRecord()
    {
        return ['created'];
    }

    protected static function bootRecordsActivity()
    {
        if (auth()->guest()) return;

        foreach (static::getActivitiesToRecord() as $event) {
            static::created(function($thread) use ($event) {
                $thread->recordActivity($event);
            });
        }

        static::deleting(function($model) {
            $model->activity()->delete();
        });
    }

    protected function recordActivity($event)
    {
        $this->activity()->create([
            'user_id' => auth()->id(),
            'type' => $this->getActivityType($event),
            // 'subject_id' => $this->id,
            // 'subject_type' => get_class($this),
        ]);
    }

    public function activity()
    {
        return $this->morphMany(Activity::class, 'subject');
    }

    protected function getActivityType($event)
    {
        $type = strtolower((new \ReflectionClass($this))->getShortName());
        return "{$event}_{$type}";
    }
}